import numpy as np
import os


def compute_tanhx(data):
    data_1 = 1 + np.exp(data)
    data_2 = data_1 * data_1
    data_result = (data_2 - 1) / (data_2 + 1)
    return data_result


def mish_grad(input_grad, input_x, input_tanhx):
    if input_tanhx is None:
        exp_x = np.exp(input_x)
        exp_add_x = exp_x + 1
        rec_exp_add_x = 1.0 / (exp_add_x * exp_add_x + 1.0)
        result_1 = exp_add_x * exp_x * input_x * rec_exp_add_x * rec_exp_add_x * 4
        result = result_1 - 2 * rec_exp_add_x + 1
    else:
        pow_input_tanhx = input_tanhx * input_tanhx
        result = input_tanhx + input_x * (1 - pow_input_tanhx) * np.exp(input_x) / (1 + np.exp(input_x))
    result = result * input_grad
    return [result, ]


def gen_golden_data_simple():
    test_type = np.float16
    shape = [32]
    input_grad = np.random.uniform(-1, 1, shape).astype(test_type)
    input_x = np.random.uniform(-1, 1, shape).astype(test_type)
    input_tanhx = np.random.uniform(-1, 1, shape).astype(test_type)
    res = mish_grad(input_grad, input_x, input_tanhx)
    golden = np.array(res).astype(test_type).reshape(shape)
    print(golden)
    os.system("mkdir -p input")
    os.system("mkdir -p output")
    input_grad.tofile("./input/input_grad.bin")
    input_x.tofile("./input/input_x.bin")
    input_tanhx.tofile("./input/input_tanhx.bin")
    golden.tofile("./output/golden.bin")


if __name__ == "__main__":
    gen_golden_data_simple()
